if(!window.mc){
	window.mc = function(){};
}
mc.check_load = function(){
	if(!mc.template){
		mc.error = "mc.template no loaded";
		return false;
	}
	if(!mc.panel){
		mc.error = "mc.panel no loaded";
		return false;
	}
	if(!mc.inputer){
		mc.error = "mc.inputer no loaded";
		return false;
	}
	if(!mc.tape){
		mc.error = "mc.tape no loaded";
		return false;
	}
	if(!mc.transport){
		mc.error = "mc.transport no loaded";
		return false;
	}
	if(!mc.translate){
		mc.error = "mc.translate no loaded";
		return false;
	}
	if(!mc.smiles){
		mc.error = "mc.smiles no loaded";
		return false;
	}
	if(!mc.cmd){
		mc.error = "mc.cmd no loaded";
		return false;
	}
	return true;
}
mc.start = function(p){
	if(!mc.main.check(p)){
		return;
	}
	mc.main.init(p);
	mc.start_ping();
	if(p.extra_data){
		mc.extra_data = p.extra_data;
	}
	if(p.run){
		mc.template.process(p.run,p.run_data,$("<div/>").appendTo("#main"),
						function(){
							$("#main").css("height","auto");
							$("#main").delay(50).queue(
								function(next){
									$(window).trigger("resize");
									next();
								});
						});
		if(p.start){
			mc.template.load(p.run,
				function(){
					p.start(p.start_data);
				});
		}
	}else if(p.start){
		p.start(p.start_data);
	}
	mc.main.call_login();
}
mc.start_ping = function(){
	var to = mc.main.ping_interval * 1000;
	
	var on_data;
	var on_ping = function(){
		mc.request("ping",[],on_data);
	}

	on_data = function(data){
		if(data && (!data.errror || data.type == "http")){
			window.setTimeout(on_ping,to);
		}
	};
	on_ping();
}
mc.ts = function(time){
	return (time ? new Date(time*1000) : new Date()).toLocaleTimeString().match(/(\d+:\d+:\d+)/)[1];
}
mc.prof = function(obj){
	if(!obj){
		obj = [ new Date() ];
	}else{
		obj.push(new Date());
	}
	return obj;
}
mc.prof_str = function(obj){
	var res = [];
	for(var i = 1; i < obj.length;i++){
		res.push(obj[i].getTime() - obj[i-1].getTime());
	}
	return res.join(", ");
}
mc.request = function(file,data,callback,context,cb_error){
	var param = {
		context: context || mc,
		url: "/" + file + ".pl",
		type: "POST",
		data: data,
		dataType: "json",
		success: mc.request.callback(callback,cb_error)
	};
	if(cb_error){
		param.error = function(e){
			cb_error.call(this,{error:e.error,type:"http"});
		}
	}else{
		param.error = function(e){
			mc.tape.put_console("http_error: " + e.status);
		}
	}
	return $.ajax(param);
}
mc.request.callback = function(cb,ecb){
	if(ecb){
		return function(data){
			if(data && !data.error){
				cb.call(this,data);
			}else{
				ecb.call(this,data);
			}
		}
	}else{
		return function(data){
			if(data && !data.error){
				cb.call(this,data);
			}else{
				mc.tape.put_console("data_error: " + data.text);
			}
		}
	}
}
